<?php

namespace app\admin\controller\place_order;

use app\common\controller\Backend;
use app\admin\model\Order as OrderModel;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Config;
use think\facade\Db;
use Exception;

class PlaceOrder extends Backend {
    protected object $model;

    // 排除字段
    protected array|string $preExcludeFields = ['updatetime', 'createtime'];

    protected array|string $quickSearchField = 'name';

    protected array $seller = [];
    protected array $color = [];
    protected array $size = [];
    protected array $category = [];

    public function initialize():void {
        parent::initialize();
        $this->model = new OrderModel();
        $this->seller = Config::get('custom.seller');
        $this->color = Config::get('custom.color');
        $this->size = Config::get('custom.size');
        $this->category = Config::get('custom.category');
    }


    /**
     * 复制一条数据
     */
    public function copyOrder():void {
        $id = $this->request->param('id');
        $data = $this->model->find($id)->toArray();
//        print_r($data);die;
        unset($data['id']);
        $data['create_time'] = $this->timestamp;
        $result = $this->model->save($data);
        if($result){
            $this->success();
        }else{
            $this->error();
        }
    }

    public function index():void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model->where(['draft' => 1])
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        foreach ($where as $val) {
            if ($val[0] == 'order.user_id') $user_id = $val[2];
        }

        $list = $res->items();

        foreach ($list as &$val) {
            $val['supplement_images'] = empty($val['supplement_images']) ? [] : $val['supplement_images'];
            $val['seller'] = str_replace(',', '/', $val['seller']) . '/' . $val['house_number'] . '<br>(' . $val['seller_name'] . ')';
            $category = explode(',', $val['category']);
            $val['category'] = count($category) == 2 ? $category[1] : $val['category'];
        }

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function add():void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            if (empty($data['seller'])) $this->error('请选择商家号');
            $data['seller'] = array_filter($data['seller']);
            if (empty($data['seller'])) $this->error('请选择商家号');
            if (empty($data['house_number'])) $this->error('请输入门牌号');
            if (empty($data['seller_name'])) $this->error('请输入商家名');
            if (empty($data['color'])) $this->error('请输入颜色');
            if (empty($data['size'])) $this->error('请输入尺码');
            if (empty($data['category'])) $this->error('请选择分类');
            if (empty($data['number'])) $this->error('请输入采购数量');
            if (empty($data['purchase_price'])) $this->error('请输入采购价格');

            //            print_r($data);die;

            $data['seller'] = implode(',', $data['seller']);
            $data['category'] = implode(',', $data['category']);
            $data['supplement_images'] = empty($data['supplement_images']) ? '' : implode(',', $data['supplement_images']);

            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }

                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->success('', [
            'seller' => $this->seller,
            'color' => $this->color,
            'size' => $this->size,
            'category' => $this->category,
        ]);
    }

    public function edit():void {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $row['seller'] = explode(',', $row['seller']);
        $row['category'] = explode(',', $row['category']);

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);


            if (empty($data['seller'])) $this->error('请选择商家号');
            $data['seller'] = array_filter($data['seller']);
            if (empty($data['seller'])) $this->error('请选择商家号');
            if (empty($data['house_number'])) $this->error('请输入门牌号');
            if (empty($data['seller_name'])) $this->error('请输入商家名');
            if (empty($data['color'])) $this->error('请输入颜色');
            if (empty($data['size'])) $this->error('请输入尺码');
            if (empty($data['category'])) $this->error('请选择分类');
            if (empty($data['number'])) $this->error('请输入采购数量');
            if (empty($data['purchase_price'])) $this->error('请输入采购价格');

            //            print_r($data);die;

            $data['seller'] = implode(',', $data['seller']);
            $data['category'] = implode(',', $data['category']);


            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }

        }

        $this->success('', [
            'row' => $row
        ]);
    }


    /**
     * 下单页面获取remarks处信息
     */
    public function getRemarks(){
        $params = $this->request->get();
        $user = Db::name('user')->where(['id' => $params['user_id']])->find();
        $place_order_type = db::name('place_order_type')->where(['id' => $params['place_order_type_id']])->find();
        $parent_place_order_type = db::name('place_order_type')->where(['id' => $place_order_type['pid']])->find();
        $this->success('', [
            'user' => $user,
            'place_order_type' => $place_order_type,
            'parent_place_order_type' => $parent_place_order_type
        ]);
    }


}